package com.wanyangproject.activity;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.TextOptions;
import com.baidu.mapapi.map.TextureMapView;
import com.baidu.mapapi.model.LatLng;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.wanyangproject.R;
import com.wanyangproject.adapter.FenLeiZiXunAdapter;
import com.wanyangproject.entity.FenLeititleEntity;
import com.wanyangproject.entity.LiuYanFanKuiEntity;
import com.wanyangproject.shouye.YuanQuJieShaoActivity;
import com.wanyangproject.shouye.ZiXunXiangQingActivity;
import com.wanyangproject.utils.ContractUtils;
import com.wanyangproject.utils.WebViewUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

public class YuanQuZhaoShangFenLeiActivity extends AppCompatActivity {

    @BindView(R.id.image_back)
    ImageView imageBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_tijiao)
    TextView tvTijiao;
    @BindView(R.id.phone)
    RelativeLayout phone;
    @BindView(R.id.tv_address)
    TextView tvAddress;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.et_liuyan_neirong)
    EditText etLiuyanNeirong;
    @BindView(R.id.image)
    ImageView image;
    @BindView(R.id.webView)
    WebView webView;
    @BindView(R.id.scorllView)
    ScrollView scorllView;
    //    @BindView(R.id.main_map)
//    TextureMapView mainMap;
//    @BindView(R.id.main_map)
//    MapView mainMap;
    private TextureMapView mainMap;

    private String id;
    private String typeid;
    private String content;
    private WebSettings mWebSettings;
    private FenLeititleEntity fenLeititleEntity;
    private FenLeiZiXunAdapter fenLeiZiXunAdapter;
    private BaiduMap map;
    private String lat;
    private String lng;
    private double weidu;
    private double jingdu;
    private String name;
    private String zixuntypeid;
    private static Boolean isOK = false;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_yuanu_zhaoshang_fen_lei);
        ButterKnife.bind(this);


        Intent intent = getIntent();
        id = intent.getStringExtra("id");
        typeid = intent.getStringExtra("typeid");
        zixuntypeid = intent.getStringExtra("zixuntypeid");//分类资讯的typeID
        System.out.println(typeid + "           ");
        System.out.println(id + "         园区招商接收id");


//        lat = intent.getStringExtra("lat");//经度
//        lng = intent.getStringExtra("lng");//纬度
//        name = intent.getStringExtra("name");
//
//        System.out.println(name+"    name");

//        System.out.println(lat+"         lat");
//        System.out.println(lng+"           lng");
//



        mWebSettings = webView.getSettings();
        mWebSettings.setJavaScriptEnabled(true);  //允许加载javascript
        webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webView.getSettings().setLoadWithOverviewMode(true);
        mWebSettings.setSupportZoom(false);     //允许缩放
        mWebSettings.setBuiltInZoomControls(false); //原网页基础上缩放
        mWebSettings.setUseWideViewPort(false);   //任意比例缩放
//        mWebSettings.setUseWideViewPort(true); //将图片调整到适合webview的大小
//        mWebSettings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小
        // 支持通过JS打开新窗口
        mWebSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        mWebSettings.setLoadWithOverviewMode(true);
        //不显示webview缩放按钮
        mWebSettings.setDisplayZoomControls(false);
        webView.setLayerType(View.LAYER_TYPE_HARDWARE,null);//开启硬件加速
//        String cacheDirPath = getFilesDir().getAbsolutePath() + APP_CACAHE_DIRNAME;
//      String cacheDirPath = getCacheDir().getAbsolutePath()+Constant.APP_DB_DIRNAME;
        //设置数据库缓存路径
//        webView.getSettings().setDatabasePath(cacheDirPath);
        //设置  Application Caches 缓存目录
//        webView.getSettings().setAppCachePath(cacheDirPath);
        //开启 Application Caches 功能
        webView.getSettings().setAppCacheEnabled(true);
        webView.setWebViewClient(new WebViewClient());
        mWebSettings.setDomStorageEnabled(true);
        mWebSettings.setDatabaseEnabled(true);

        //        webView.setWebChromeClient(new WebChromeClient());
        webView.addJavascriptInterface(new JavaScriptInterface(), "JSInterface");


        //        园区招商标题的网路请求
        initBiaoTiHttp();


        initView();


        //        地图初始化
        initDiTuView();


        //        权限
        initinit();


//


    }


    //    权限
    private void initinit() {
        if (Build.VERSION.SDK_INT >= 23) {
            if (ActivityCompat.checkSelfPermission(YuanQuZhaoShangFenLeiActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION)
                    != PackageManager.PERMISSION_GRANTED
                    || ActivityCompat.checkSelfPermission(YuanQuZhaoShangFenLeiActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)
                    != PackageManager.PERMISSION_GRANTED
                    || ActivityCompat.checkSelfPermission(YuanQuZhaoShangFenLeiActivity.this, Manifest.permission.READ_PHONE_STATE)
                    != PackageManager.PERMISSION_GRANTED) {
//                Toast.makeText(getContext(), "没有权限,请手动开启定位权限", Toast.LENGTH_SHORT).show();
                // 申请一个（或多个）权限，并提供用于回调返回的获取码（用户定义）
                requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.READ_PHONE_STATE}, 100);
            } else {
//                initLoc();
                System.out.println("定位11111");
            }
        } else {
//            initLoc();
            System.out.println("定位2222222");
        }
    }


    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mainMap.onSaveInstanceState(outState);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mainMap.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mainMap.onPause();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        mainMap.onDestroy();
        map.setMyLocationEnabled(false);
    }




    private void initDiTuView() {
        mainMap = (TextureMapView) findViewById(R.id.main_map);
//        获取Bitmap对象
        map = mainMap.getMap();
        map.setMapType(BaiduMap.MAP_TYPE_NORMAL);

//        mainMap.setOnTouchListener(new View.OnTouchListener() {
//            @Override
//            public boolean onTouch(View v, MotionEvent event) {
//                if (event.getAction() == MotionEvent.ACTION_UP) {
//                    scorllView.requestDisallowInterceptTouchEvent(false);
//                } else {
//                    scorllView.requestDisallowInterceptTouchEvent(true);
//                }
//                return false;
//            }
//        });


//        System.out.println(fenLeititleEntity.getResponse().getInfo().getLatitude()+"         1111111");
//        System.out.println(fenLeititleEntity.getResponse().getInfo().getLongitude()+"       2222222");
//




//
//        //定义文字所显示的坐标点
//
//        if (fenLeititleEntity == null) {
//            return;
//        }
//        if (fenLeititleEntity.getResponse().getInfo().getLatitude().equals("") || fenLeititleEntity.getResponse().getInfo().getLongitude().equals("")) {
//            return;
//        }
//        jingdu = Double.parseDouble(fenLeititleEntity.getResponse().getInfo().getLatitude());
//        weidu = Double.parseDouble(fenLeititleEntity.getResponse().getInfo().getLongitude());
//
//        LatLng llText = new LatLng(weidu, jingdu);
//
////      构建文字Option对象，用于在地图上添加文字
//        OverlayOptions textOption = new TextOptions()
////                .bgColor(0xAAFFFF00)
//                .fontSize(30)
////                .fontColor(0xFFFF00FF)
////                .text(name)
//                .rotate(-30)
//                .position(llText);
//
////     在地图上添加该文字对象并显示
//        map.addOverlay(textOption);
    }



    private void initView() {
        webView.setWebViewClient(new WebViewClient() {
            /**
             * 拦截 url 跳转,在里边添加点击链接跳转或者操作
             */
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                System.out.println("xxxxxxxxxxxxxxxxxxxxxxxxxx");
                return WebViewUtils.shouldOverrideUrlLoading(view, request, YuanQuZhaoShangFenLeiActivity.this);
            }


            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                System.out.println("66666666666666666666");
                return WebViewUtils.shouldOverrideUrlLoading(view, url, YuanQuZhaoShangFenLeiActivity.this);

            }


            /**
             * 在开始加载网页时会回调
             */
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                System.out.println("7777777777777");
                System.out.println(url + "          url");
                System.out.println(view + "           view");
                System.out.println(favicon + "             favicon");
            }

            /**
             * 加载错误的时候会回调，在其中可做错误处理，比如再请求加载一次，或者提示404的错误页面
             */
            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                super.onReceivedError(view, request, error);

            }


            /**
             * 在结束加载网页时会回调
             */
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                System.out.println("chenggongchenggongchenggong");

            }

            /**
             * 当接收到https错误时，会回调此函数，在其中可以做错误处理
             */
            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
            }

            /**
             * 在每一次请求资源时，都会通过这个函数来回调
             */
            public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
                return null;
            }


            @Override
            public void onPageCommitVisible(WebView view, String url) {
                super.onPageCommitVisible(view, url);

            }
        });
    }


    private Bitmap getBitmapFromView(View view) {
        view.destroyDrawingCache();
        view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.UNSPECIFIED);
        view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
        view.setDrawingCacheEnabled(true);
        Bitmap bitmap = view.getDrawingCache();
        return bitmap;
    }



    //    园区招商标题的网路请求
    private void initBiaoTiHttp() {
        OkHttpUtils.post()
                .url(ContractUtils.LOGIN_URL + "news/getCateInfo")
                .addHeader("token", ContractUtils.getTOKEN(YuanQuZhaoShangFenLeiActivity.this))
                .addParams("typeId", id)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        System.out.println(response + "        园区招商标题的网路请求 ");
                        ContractUtils.Code500(YuanQuZhaoShangFenLeiActivity.this, response);
                        if (response.indexOf("200") != -1) {
                            Gson gson = new Gson();
                            fenLeititleEntity = gson.fromJson(response, FenLeititleEntity.class);


                            if (fenLeititleEntity == null) {
                                return;
                            }

                            if (fenLeititleEntity.getResponse().getInfo().getLatitude().equals("") || fenLeititleEntity.getResponse().getInfo().getLongitude().equals("")) {
//                                return;
                            }else{
                                jingdu = Double.parseDouble(fenLeititleEntity.getResponse().getInfo().getLatitude());
                                weidu = Double.parseDouble(fenLeititleEntity.getResponse().getInfo().getLongitude());
                                //设置经纬度（参数一是纬度，参数二是经度）
                                MapStatusUpdate mapstatusupdate = MapStatusUpdateFactory.newLatLng(new LatLng(jingdu, weidu));
                                //对地图的中心点进行更新，
                                map.setMapStatus(mapstatusupdate);


                                LatLng point = new LatLng(jingdu, weidu);

//                             构建Marker图标
//                            BitmapDescriptor bitmap = BitmapDescriptorFactory
//                                    .fromResource(R.drawable.dingwei);

//                           构建MarkerOption，用于在地图上添加Marker



                                View view = LayoutInflater.from(YuanQuZhaoShangFenLeiActivity.this).inflate(R.layout.baiduditu_maker, null);
                                TextView tv_name=view.findViewById(R.id.tv_name);
                                tv_name.setText(fenLeititleEntity.getResponse().getInfo().getAddress());
                                BitmapDescriptor bitmap = BitmapDescriptorFactory.fromBitmap(getBitmapFromView(view));

                                OverlayOptions option = new MarkerOptions()
//                                 .title(name)
                                        .position(point)
                                        .icon(bitmap);

//                        在地图上添加Marker，并显示
                                map.addOverlay(option);

                            }


//                            jingdu = Double.parseDouble(fenLeititleEntity.getResponse().getInfo().getLatitude());
//                            weidu = Double.parseDouble(fenLeititleEntity.getResponse().getInfo().getLongitude());
//                            //设置经纬度（参数一是纬度，参数二是经度）
//                            MapStatusUpdate mapstatusupdate = MapStatusUpdateFactory.newLatLng(new LatLng(jingdu, weidu));
//                            //对地图的中心点进行更新，
//                            map.setMapStatus(mapstatusupdate);
//
//
//                            LatLng point = new LatLng(jingdu, weidu);
//
////                             构建Marker图标
////                            BitmapDescriptor bitmap = BitmapDescriptorFactory
////                                    .fromResource(R.drawable.dingwei);
//
////                        构建MarkerOption，用于在地图上添加Marker
//
//
//
//
//
//
//                            View view = LayoutInflater.from(YuanQuZhaoShangFenLeiActivity.this).inflate(R.layout.baiduditu_maker, null);
//                            TextView tv_name=view.findViewById(R.id.tv_name);
//                            tv_name.setText(fenLeititleEntity.getResponse().getInfo().getAddress());
//                            BitmapDescriptor bitmap = BitmapDescriptorFactory.fromBitmap(getBitmapFromView(view));
//
//                            OverlayOptions option = new MarkerOptions()
////                                 .title(name)
//                                    .position(point)
//                                    .icon(bitmap);
//
////                        在地图上添加Marker，并显示
//                            map.addOverlay(option);


                            if (fenLeititleEntity.getResponse().getInfo().getBackground() == null) {

                            } else {//背景图
                                Glide.with(YuanQuZhaoShangFenLeiActivity.this).load(fenLeititleEntity.getResponse().getInfo().getBackground()).into(image);
                            }


                            if (fenLeititleEntity.getResponse().getInfo().getTitle() == null) {

                            } else {
                                tvTitle.setText(fenLeititleEntity.getResponse().getInfo().getTitle());
                            }


                            if (fenLeititleEntity.getResponse().getInfo().getContent() == null) {

                            } else {
                                //                            内容
                                content = fenLeititleEntity.getResponse().getInfo().getContent();
                                webView.loadDataWithBaseURL("http://www.baidu.com", getNewContent(content), "text/html", "UTF-8", null);

                            }


                            if (fenLeititleEntity.getResponse().getInfo().getAddress() == null) {

                            } else {
                                tvAddress.setText("地址：" + fenLeititleEntity.getResponse().getInfo().getAddress());
                            }


                            fenLeiZiXunAdapter = new FenLeiZiXunAdapter(YuanQuZhaoShangFenLeiActivity.this, fenLeititleEntity.getResponse().getList());
                            LinearLayoutManager manager = new LinearLayoutManager(YuanQuZhaoShangFenLeiActivity.this);
                            recyclerView.setLayoutManager(manager);
                            recyclerView.setAdapter(fenLeiZiXunAdapter);


//                            点击分类进详情
                            fenLeiZiXunAdapter.setXiangQingClick(new FenLeiZiXunAdapter.XiangQingClick() {
                                @Override
                                public void xiangqingClick(int position, String id) {
//                                    Intent intent = new Intent(YuanQuZhaoShangFenLeiActivity.this, ZhengCeFaGuiXiangQingActivity.class);
                                    Intent intent = new Intent(YuanQuZhaoShangFenLeiActivity.this, YuanQuZhaoShangXiangQingActivity.class);
                                    intent.putExtra("id", id);
                                    intent.putExtra("typeId",zixuntypeid);
                                    startActivity(intent);
                                }
                            });


                        }
                    }
                });
    }


    /**
     * 将html文本内容中包含img标签的图片，宽度变为屏幕宽度，高度根据宽度比例自适应
     **/
    public static String getNewContent(String htmltext) {

//        if(isOK == false){
//            return htmltext;
//        }
//
//        isOK = true;
        try {
            Document doc = Jsoup.parse(htmltext);
            Elements elements = doc.getElementsByTag("img");
            for (Element element : elements) {
                element.attr("width", "100%").attr("height", "auto");
            }

            return doc.toString();
        } catch (Exception e) {
            return htmltext;
        }
    }


    @OnClick({R.id.image_back, R.id.tv_title, R.id.tv_tijiao, R.id.phone, R.id.tv_address, R.id.recyclerView})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.image_back:
                finish();
                break;
            case R.id.tv_title:
                break;
            case R.id.tv_tijiao:
                if (etLiuyanNeirong.getText().toString().trim().equals("")) {
                    Toast.makeText(this, "请输入留言内容", Toast.LENGTH_SHORT).show();
                } else {
//                    园区招商留言内容的网络请求
                    initLiuYanHttp();
                }
                break;
            case R.id.phone:

                //     打电话累计的接口的网络请求
                initDaDianHuaLeiJiHttP();

                //                判断当前SDK版本号
                if (Build.VERSION.SDK_INT >= 23) {
//                    当前拨打电话权限是没有给的
                    if (ContextCompat.checkSelfPermission(YuanQuZhaoShangFenLeiActivity.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
//                        我要请求权限
                        ActivityCompat.requestPermissions(YuanQuZhaoShangFenLeiActivity.this, new String[]{Manifest.permission.CALL_PHONE}, 1);
                    } else {
                        call();
                    }
                } else {
                    call();
                }
                break;
            case R.id.tv_address:
                break;
            case R.id.recyclerView:
                break;
        }
    }


    //    打电话累计的接口的网络请求
    private void initDaDianHuaLeiJiHttP() {
        OkHttpUtils.post()
                .url(ContractUtils.LOGIN_URL + "news/zhaoshangPhoneRet")
                .addHeader("token", ContractUtils.getTOKEN(YuanQuZhaoShangFenLeiActivity.this))
                .addParams("id", id)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        System.out.println(response + "                 打电话累计的接口的网络请求 ");
                        ContractUtils.Code500(YuanQuZhaoShangFenLeiActivity.this, response);
                    }
                });
    }


    public void call() {
        try {
            Intent intent = new Intent(Intent.ACTION_CALL);
            intent.setData(Uri.parse("tel:" + fenLeititleEntity.getResponse().getInfo().getPhone()));
            startActivity(intent);
        } catch (SecurityException e) {
            e.printStackTrace();
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 1:
                if (permissions.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    call();
                } else {
                    Toast.makeText(YuanQuZhaoShangFenLeiActivity.this, "您拒绝拨打电话", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }


    //    园区招商留言内容的网络请求
    private void initLiuYanHttp() {
        OkHttpUtils.post()
                .url(ContractUtils.LOGIN_URL + "news/feedback")
                .addHeader("token", ContractUtils.getTOKEN(YuanQuZhaoShangFenLeiActivity.this))
                .addParams("parkId", ContractUtils.getParkId(YuanQuZhaoShangFenLeiActivity.this))
                .addParams("typeId", id)
                .addParams("content", etLiuyanNeirong.getText().toString().trim())
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {

                    }

                    @Override
                    public void onResponse(String response, int id) {
                        System.out.println(response + "           ");
                        ContractUtils.Code500(YuanQuZhaoShangFenLeiActivity.this, response);
                        if (response.indexOf("200") != -1) {
                            Gson gson = new Gson();
                            LiuYanFanKuiEntity liuYanFanKuiEntity = gson.fromJson(response, LiuYanFanKuiEntity.class);
                            Toast.makeText(YuanQuZhaoShangFenLeiActivity.this, "发表成功", Toast.LENGTH_SHORT).show();
                            finish();
                        }
                    }
                });
    }


    class JavaScriptInterface {
        @JavascriptInterface
        public void processFormInputs(String html) {
//            LogUtils.e("html-->" + html);
            System.out.println(html);
        }
    }


}
